/**
 * $Id$
 *
 * Copyright (c) 2014 ChinaSoft International, Ltd. All rights reserved
 * JointForce Project
 *
 */
package com.csi.jf.crucible.api.crucible;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.icss.j2ee.util.http.HttpClientException;

/**
 * @Title: RestClient.java
 * @Description: <br>
 *               <br>
 * @Company: Chinasofti
 * @Created on 2014-7-4 下午3:19:50
 * @author zhangmh
 * @version $Revision: 1.0 $
 * @since 1.0
 */
public class RestClient {
    
    public static final String CRUCIBLE_HOST = "http://115.29.76.124:8060";
    public static final String CRUCIBLE_AUTH_TOKEN = "FEAUTH=zhangmh:4:31b8dd8276ef06615e0b8b3018c78f45";
    //private static final String CRUCIBLE_AUTH_TOKEN = "FEAUTH=zhangmh:2:d249481bd97fc34edc6e855731168517";

    private String host;
    private String authorization;
    public RestClient(){
        this.host = CRUCIBLE_HOST;
    }
    
    public RestClient(String host){
        this.host = host;
    }
    
    public RestClient(String host,String authorization){
        this.host = host;
        this.authorization = authorization;
    }
    
    public String doGet(String url) throws HttpClientException, IOException{
        return doGet(url, true);
    }
    /**
     * <p>发送HTTP GEt请求</p>
     * @param SONAR_URL
     * @throws HttpClientException
     * @throws IOException
     */
    public String doGet(String url,boolean useToken) throws HttpClientException, IOException{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            url = this.checkUrl(url,useToken);
            HttpGet httpGet = new HttpGet(url);
            System.out.println("****************************************************\n");
            System.out.println("do get request for:\n"+url);
            
            //add authentication info
            //String user = Base64.encode("zhangmh".getBytes());
            //String pass = Base64.encode("8820320".getBytes());
            httpGet.setHeader("Accept","application/json");
            if(this.authorization!=null){
                httpGet.setHeader("Authorization",this.authorization);
            }
            //httpGet.setHeader("Authorization", "Basic."+user+":"+pass);
            
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            response1.addHeader("content-type", "application/json");
            response1.addHeader("accept", "application/json");
            
//            StringBuilder sb = new StringBuilder();
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();
//                EntityUtils.consume(entity1);
                String retStr = null;
                if(entity1!=null){
                    retStr = EntityUtils.toString(entity1) ;
//                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity1.getContent()));
//                    String line = null;
//                    while((line=reader.readLine())!=null){
//                        sb.append(line+"\n");
//                    }
//                    reader.close();
//                    System.out.println("Response:"+sb.toString());
                    System.out.println("Response:"+retStr);
                    System.out.println("Length:"+entity1.getContentLength());
                    System.out.println("ContentType:"+entity1.getContentType());
                    System.out.println("Encoding:"+entity1.getContentEncoding());
                    return retStr;
                }
            } finally {
                response1.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpclient.close();
        }
        return null;
    }
    
    public String doPost(String url,String json) throws HttpClientException, IOException{
        return doPost(url, json, true);
    }
    
    public String doPost(String url,String json,boolean useToken) throws HttpClientException, IOException{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            url = this.checkUrl(url,useToken);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("content-type","application/json");
//          httpPost.setHeader("content-type","application/json;charset=UTF-8");
            httpPost.setHeader("Accept", "*/*");
            httpPost.setHeader("Accept-Language", "zh-cn");
            httpPost.setHeader("Cache-Control", "no-cache");
            httpPost.setHeader("Accept-Charset", "UTF-8;");
            httpPost.setHeader("Accept","application/json");
            if(this.authorization!=null){
                httpPost.setHeader("Authorization",this.authorization);
            }
            System.out.println("****************************************************\n");
            System.out.println("do post request for:\n"+url);
            
//            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
//            nvps.add(new BasicNameValuePair("username", "vip"));
//            nvps.add(new BasicNameValuePair("password", "secret"));
//            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            
            System.out.println("do post data:\n"+json);
//            json = URLEncoder.encode(json,"UTF-8");
            HttpEntity entity = new StringEntity(json, Charset.forName("utf-8"));
//            HttpEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);
            
            CloseableHttpResponse response1 = httpclient.execute(httpPost);
            response1.addHeader("content-type", "application/json");
//            response1.setHeader("content-type","application/json;charset=UTF-8");
            response1.addHeader("Accept", "application/json");
//          response1.setHeader("Accept-Charset", "UTF-8;");
            
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();
                String retStr = null;
                if(entity1!=null){
                    retStr = EntityUtils.toString(entity1) ;
                    System.out.println("Response:"+retStr);
                    System.out.println("Length:"+entity1.getContentLength());
                    System.out.println("ContentType:"+entity1.getContentType());
                    System.out.println("Encoding:"+entity1.getContentEncoding());
                    return retStr;
                }
            } finally {
                response1.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpclient.close();
        }
        return null;
    }
    
    public String doDelete(String url) throws HttpClientException, IOException{
        return doDelete(url, true);
    }
    
    public String doDelete(String url,boolean useToken) throws HttpClientException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            url = this.checkUrl(url,useToken);
            HttpDelete httpDelete = new HttpDelete(url);
            httpDelete.setHeader("Accept","application/json");
            if(this.authorization!=null){
                httpDelete.setHeader("Authorization",this.authorization);
            }
            System.out.println("****************************************************\n");
            System.out.println("do delete request for:\n"+url);
            
            CloseableHttpResponse response1 = httpclient.execute(httpDelete);
            response1.addHeader("content-type", "application/json");
            response1.addHeader("accept", "application/json");
            
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();
                String retStr = null; 
                if(entity1!=null){
                    retStr = EntityUtils.toString(entity1) ;  
                    System.out.println("Response:"+retStr);
                    System.out.println("Length:"+entity1.getContentLength());
                    System.out.println("ContentType:"+entity1.getContentType());
                    System.out.println("Encoding:"+entity1.getContentEncoding());
                    return retStr;
                }
            } finally {
                response1.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpclient.close();
        }
        return null;
    }
    
    public String doPut(String url,String json) throws HttpClientException, IOException{
        return doPut(url, json ,true);
    }

    public String doPut(String url,String json,boolean useToken) throws HttpClientException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            url = this.checkUrl(url,useToken);
            HttpPut httpPut = new HttpPut(url);
            httpPut.setHeader("content-type","application/json");
            httpPut.setHeader("Accept","application/json");
            if(this.authorization!=null){
                httpPut.setHeader("Authorization",this.authorization);
            }
            System.out.println("****************************************************\n");
            System.out.println("do put request for:\n"+url);
            
            HttpEntity entity = new StringEntity(json);
            httpPut.setEntity(entity);
            
            CloseableHttpResponse response1 = httpclient.execute(httpPut);
            response1.addHeader("content-type", "application/json");
            response1.addHeader("accept", "application/json");
            
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();
                String retStr = null;
                if(entity1!=null){
                    retStr = EntityUtils.toString(entity1) ;
                    System.out.println("Response:"+retStr);
                    System.out.println("Length:"+entity1.getContentLength());
                    System.out.println("ContentType:"+entity1.getContentType());
                    System.out.println("Encoding:"+entity1.getContentEncoding());
                    return retStr;
                }
            } finally {
                response1.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpclient.close();
        }
        return null;
    }
    
    private String checkUrl(String url,boolean useToken){
        if(url!=null && !url.startsWith("http")){
            url = this.host + url;
        }
        if(useToken && url!=null && url.indexOf("FEAUTH=")<0){
            if(url.indexOf("?")<0){
                url= url + "?" + CRUCIBLE_AUTH_TOKEN;
            }else{
                url= url + "&" + CRUCIBLE_AUTH_TOKEN;
            }
        }
        return url;
    }
}
